<!-- 文件: src/components/SetObjectAclDialog.vue -->
<template>
    <el-dialog :model-value="visible" title="设置文件读写权限" width="500px"
        @update:modelValue="$emit('update:visible', $event)" :close-on-click-modal="false">
        <div v-if="loadingInitialAcl" class="acl-loading">
            <el-icon class="is-loading">
                <Loading />
            </el-icon>
            <span>正在获取当前权限...</span>
        </div>

        <el-form v-else label-position="top">
            <el-form-item label="文件ACL">
                <el-radio-group v-model="selectedAcl">
                    <el-radio value="private">私有</el-radio>
                    <el-radio value="public-read">公共读</el-radio>
                    <el-radio value="public-read-write">公共读写</el-radio>
                    <el-radio value="authenticated-read">授权用户读</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-text type="info" class="acl-description">{{ aclDescription }}</el-text>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="$emit('update:visible', false)">取消</el-button>
                <el-button type="primary" @click="handleSave" :loading="isSaving">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import apiClient from '@/api';
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';

const props = defineProps({
    visible: Boolean,
    bucketName: String,
    objectKey: String,
    // 【优化】我们不再需要从外部传入 currentAcl
    // currentAcl: String, 
});
const emit = defineEmits(['update:visible', 'success']);

const selectedAcl = ref('private');
const isSaving = ref(false);
const loadingInitialAcl = ref(false);

// 为每个ACL选项提供详细描述
const aclDescriptions = {
    private: '私有：对文件的所有访问都需要进行身份验证。',
    'public-read': '公共读：任何人（包括匿名用户）都可以读取该文件。',
    'public-read-write': '（高风险）公共读写：任何人都可以读、写、删除该文件。',
    'authenticated-read': '授权用户读：所有通过身份验证的用户（无论是否为您账户下的）都有读取权限。'
};

const aclDescription = computed(() => aclDescriptions[selectedAcl.value]);

// 【核心逻辑】当对话框变得可见时，自动去获取文件当前的真实ACL
watch(() => props.visible, (newVal) => {
    if (newVal && props.bucketName && props.objectKey) {
        fetchCurrentObjectAcl();
    }
});

// 新增：获取当前对象ACL的函数
const fetchCurrentObjectAcl = async () => {
    loadingInitialAcl.value = true;
    try {
        // 我们复用 get_object_details 接口来获取信息
        const response = await apiClient.get(`/api/v1/buckets/${props.bucketName}/objects/details`, {
            params: { key: props.objectKey }
        });
        // 将单选框的默认选中项，设置为文件当前的真实ACL
        selectedAcl.value = response.data.object_acl || 'private';
    } catch (error) {
        ElMessage.error('获取当前文件权限失败');
        // 如果失败，安全起见，默认选中 'private'
        selectedAcl.value = 'private';
    } finally {
        loadingInitialAcl.value = false;
    }
};


// 保存新ACL的函数
const handleSave = async () => {
    if (!props.bucketName || !props.objectKey) {
        ElMessage.error('缺少必要信息');
        return;
    }
    isSaving.value = true;
    try {
        // 调用我们新创建的 set_object_acl 接口
        await apiClient.put(`/api/v1/buckets/${props.bucketName}/objects/acl`, {
            key: props.objectKey,
            acl: selectedAcl.value,
        });
        ElMessage.success('文件ACL设置成功！');
        emit('success'); // 通知父组件操作成功，以便刷新
        emit('update:visible', false); // 关闭对话框
    } catch (error) {
        ElMessage.error(error.response?.data?.error || '操作失败');
    } finally {
        isSaving.value = false;
    }
};
</script>

<style scoped>
.acl-description {
    display: block;
    margin-top: 8px;
    line-height: 1.5;
}

.el-radio-group {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    /* 增加选项之间的垂直间距 */
}

.acl-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    min-height: 150px;
    /* 给加载状态一个最小高度 */
    color: #606266;
}
</style>